import { ref, reactive, computed, watch, onMounted } from 'vue'
import { login as apiLogin, logout as apiLogout, changePassword as apiChangePassword, getCurrentUser } from '../api/auth'

// Create a reactive state that persists during page reloads
const user = ref(null)
const isAuthenticated = ref(false)
const isLoading = ref(false)
const error = ref(null)

// 从本地存储中恢复用户信息
const restoreUserFromStorage = () => {
  try {
    const token = localStorage.getItem('auth_token')
    const storedUser = localStorage.getItem('user_data')
    
    if (token && storedUser) {
      user.value = JSON.parse(storedUser)
      isAuthenticated.value = true
      console.log('从localStorage恢复用户信息成功:', user.value.username)
      return true
    }
    return false
  } catch (err) {
    console.error('恢复用户信息失败:', err)
    // 如果恢复失败，清除可能损坏的数据
    localStorage.removeItem('user_data')
    localStorage.removeItem('auth_token')
    isAuthenticated.value = false
    return false
  }
}

// Initialize auth state from localStorage
const initAuth = async () => {
  const token = localStorage.getItem('auth_token')
  if (!token) {
    isAuthenticated.value = false
    user.value = null
    return
  }
  
  // 从localStorage恢复用户信息
  const restored = restoreUserFromStorage()
  
  // 如果从本地存储恢复成功，且用户数据有效，则无需API调用
  if (restored && user.value && user.value.id) {
    console.log('从本地存储恢复用户认证成功')
    return
  }
  
  // 尝试从API获取最新用户数据
  try {
    isLoading.value = true
    const response = await getCurrentUser()
    user.value = response.data
    // 更新存储的用户信息
    localStorage.setItem('user_data', JSON.stringify(response.data))
    isAuthenticated.value = true
    console.log('从API获取最新用户数据成功')
  } catch (err) {
    console.error('验证令牌无效，清除认证状态:', err)
    // If token is invalid, clear authentication
    localStorage.removeItem('auth_token')
    localStorage.removeItem('user_data')
    user.value = null
    isAuthenticated.value = false
  } finally {
    isLoading.value = false
  }
}

// 监视用户状态变化，自动更新本地存储
watch(user, (newUser) => {
  if (newUser) {
    localStorage.setItem('user_data', JSON.stringify(newUser))
  }
}, { deep: true })

// 监视认证状态变化
watch(isAuthenticated, (newValue) => {
  console.log('认证状态变更:', newValue)
  if (!newValue) {
    localStorage.removeItem('auth_token')
    localStorage.removeItem('user_data')
    user.value = null
  }
})

// 立即从本地存储初始化
restoreUserFromStorage()

// 异步完成API验证
const authInitPromise = initAuth()

// For admin default account
const isDefaultAdmin = computed(() => {
  return user.value?.username === 'admin'
})

const login = async (username, password) => {
  isLoading.value = true
  error.value = null
  
  try {
    // Hard-coded admin check for the default account
    if (username === 'admin' && password === 'memeking') {
      // Simulate successful login for the default admin
      const mockResponse = {
        data: {
          token: 'mock_admin_token',
          user: {
            id: 'admin1',
            username: 'admin',
            role: 'admin'
          }
        }
      }
      
      localStorage.setItem('auth_token', mockResponse.data.token)
      localStorage.setItem('user_data', JSON.stringify(mockResponse.data.user))
      user.value = mockResponse.data.user
      isAuthenticated.value = true
      
      return mockResponse
    }
    
    // Real API call for other accounts
    const response = await apiLogin(username, password)
    localStorage.setItem('auth_token', response.data.token)
    localStorage.setItem('user_data', JSON.stringify(response.data.user))
    user.value = response.data.user
    isAuthenticated.value = true
    
    return response
  } catch (err) {
    error.value = err.response?.data?.message || '登录失败，请检查用户名和密码'
    throw error.value
  } finally {
    isLoading.value = false
  }
}

const logout = async () => {
  isLoading.value = true
  
  try {
    // Only call API if we're authenticated
    if (isAuthenticated.value) {
      await apiLogout()
    }
  } catch (err) {
    console.error('Logout error:', err)
  } finally {
    // Always clear local state
    localStorage.removeItem('auth_token')
    localStorage.removeItem('user_data')
    user.value = null
    isAuthenticated.value = false
    isLoading.value = false
  }
}

// 检查是否已登录
const checkAuth = () => {
  const token = localStorage.getItem('auth_token')
  const userData = localStorage.getItem('user_data')
  return !!(token && userData)
}

const changePassword = async (oldPassword, newPassword) => {
  isLoading.value = true
  error.value = null
  
  try {
    await apiChangePassword(oldPassword, newPassword)
  } catch (err) {
    error.value = err.response?.data?.message || '修改密码失败'
    throw error.value
  } finally {
    isLoading.value = false
  }
}

export function useAuth() {
  return {
    user,
    isAuthenticated,
    isLoading,
    error,
    isDefaultAdmin,
    login,
    logout,
    checkAuth,
    changePassword,
    authInitPromise,  // 暴露初始化Promise以便于其他组件可以等待认证完成
  }
} 